home *** CD-ROM | disk | FTP | other *** search
- Path: druid.borland.com!usenet
- From: pete@borland.com (Pete Becker)
- Newsgroups: comp.lang.c
- Subject: Re: Determining the length of an int in string form
- Date: 18 Mar 1996 15:38:12 GMT
- Organization: Borland International
- Message-ID: <4ik014$5cn@druid.borland.com>
- References: <3146D058.DD7@cbm.com>
- NNTP-Posting-Host: pbecker.borland.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <3146D058.DD7@cbm.com>, paynedc@cbm.com says...
- >
- >Consider this:
- >
- >I have a variable of type int, and I would like to use the sprintf()
- >function to write this variable to a string. However, I want to
- >dynamically allocate the space for the string, and only malloc enough
- >space to hold the int. Here's a code fragment that may illustrate this
- >more clearly:
- >
- >void func1() {
- >
- > int i = 1234;
- > char *a;
- >
- > /*
- > * We need to malloc enough space to hold "The value of i is"
- > * AND 1234. The 4 + 1 is for the 4 bytes that 1234 will occupy
- > * in the string, and for a NULL terminator.
- > */
- > a = malloc(strlen("The value of i is ") + 4 + 1);
- >
- > /*
- > * Use sprintf() to build the desired string.
- > */
- >
- > sprintf(a,"%s%d","The value of i is ",i);
- >
- > free(a);
- >
- >}
- >
- >In this example, I hardcoded the 4, because I knew that 1234 was 4
- >characters long. I would like to be able to determine this at runtime,
- >and malloc enough space accordingly.
-
- This is not hard. Think about it. How many characters are needed to display a
- value that's between 1000 and 9999? How many are needed to display a value
- that's between 10000 and 99999? See the pattern? Add one for a possible minus
- sign, and one more for the terminating 0. Or make your life simpler and
- allocate an array that's large enough to hold the text for any number. The
- space savings from doing this are rarely worth the aggravation.
- -- Pete
-
-
-